/**
* Description: 编辑设备
*
* Created by hrx on 2023/10/11
*/
<template>
  <div class="edit-device">
    <el-dialog
      :title="mode == 'add' ? '创建设备' : '编辑设备'"
      width="660px"
      v-model="dialogFormVisible"
      :append-to-body="true"
      :close-on-click-modal="false"
    >
      <el-form :model="form" :rules="rules" ref="formRef" class="form">
        <el-form-item
          :label-width="formLabelWidth"
          label="设备型号"
          prop="productId"
        >
          <el-select
            style="width: 360px; height: 36px"
            v-model="form.productId"
            placeholder="请选择"
            v-if="mode=='add'"
            clearable
          >
            <el-option
              v-for="item in deviceModeList"
              :key="item.productId"
              :label="item.productName"
              :value="item.productId"
            ></el-option>
          </el-select>
          <span v-else style="margin-left: 10px">{{ form.productName }}</span>
        </el-form-item>
        <el-form-item
          :label-width="formLabelWidth"
          label="设备编号"
          prop="deviceCode"
        >
          <el-input
            v-if="mode=='add'"
            placeholder="请输入"
            style="width: 360px; height: 36px"
            v-model="form.deviceCode"
            clearable
          ></el-input>
          <span v-else style="margin-left: 10px">{{ form.deviceCode }}</span>
        </el-form-item>
        <el-form-item
          :label-width="formLabelWidth"
          label="设备名称"
          prop="deviceName"
        >
          <el-input
            placeholder="请输入"
            style="width: 360px; height: 36px"
            v-model="form.deviceName"
            clearable
          ></el-input>
        </el-form-item>
        <el-form-item
          :label-width="formLabelWidth"
          label="所在区域"
          prop="regionList"
        >
          <el-cascader
            ref="cascaderRef"
            style="width: 360px"
            v-model="form.regionList"
            :options="regionList"
            :props="cascaderProps"
            filterable
            collapse-tags
            clearable
            class="cascader"
            placeholder="请选择所在区域"
            @change="cascaderChange"
          ></el-cascader>
        </el-form-item>
        <el-form-item
          :label-width="formLabelWidth"
          label="安装点位"
          prop="regionPositionId"
        >
          <el-select
            style="width: 360px; height: 36px"
            v-model="form.regionPositionId"
            placeholder="请选择"
            clearable
          >
            <el-option
              v-for="item in regionPositionList"
              :key="item.id"
              :label="item.positionName"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogFormVisible = false">取 消</el-button>
          <el-button type="primary" @click="submit()">确 定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">

import {reactive, ref, watch} from "vue";
import {CascaderProps, ElMessage, FormRules} from "element-plus";
import {
  type deviceDetailDTO,
  type deviceModelDTO,
  type regionTreeDTO,
  type regionPositionDTO,
  createDeviceApi,
  getRegionPositionApi, editDeviceApi
} from "@/api/device";

export interface Props {
  mode?: string,
  regionList?: Array<regionTreeDTO>,
  deviceModeList?: Array<deviceModelDTO>
}

const props = withDefaults(defineProps<Props>(), {
  mode: 'add',
  regionList: () => [],
  deviceModeList: () => []
})

const emit = defineEmits(['afterSubmit']);
const formRef = ref();
const cascaderRef = ref();
const formLabelWidth = '120px';
const dialogFormVisible = ref<boolean>(false);
const form = reactive<deviceDetailDTO>({
  id: 0,
  productId: undefined,
  deviceCode: undefined,
  deviceName: undefined,
  regionId: undefined,
  regionPositionId: undefined,
  regionList: undefined,
});
const cascaderProps: CascaderProps = {
  value: 'id',
  label: 'regionName'
}
const regionPositionList = ref<Array<regionPositionDTO>>([])
const validatorDeviceCode = (rule: any, value: any, callback: any) => {
  const reg = /^[5A-Za-z0-9-\_.:@]+$/;
  if (value.length > 32 || value.length < 4) {
    callback(new Error("请输入4-32个字符"));
  } else if (!reg.test(value)) {
    callback(new Error("只支持输入英文字母、数字及_-.:@"));
  } else {
    callback();
  }
}
const validatorRegionList = (rule: any, value: any, callback: any) => {
  if (value && cascaderRef.value.getCheckedNodes().length > 0 && cascaderRef.value.getCheckedNodes()[0].data.regionClassify == 1) {
    callback(new Error('当前选项不是区域'))
  } else {
    callback();
  }
}
const rules = reactive<FormRules>({
  productId: [
    {required: true, message: "请选择设备型号", trigger: "change"},
  ],
  deviceCode: [
    {required: true, message: "请输入设备编号", trigger: "change"},
    {validator: validatorDeviceCode, trigger: "change",},
  ],
  deviceName: [{required: false, message: "", trigger: "change"}],
  regionList: [
    {validator: validatorRegionList, trigger: "change",}
  ]
});

const cascaderChange = (val: Array<number>) => {
  if (val && val.length > 0) {
    form.regionId = val[val.length - 1];
  } else {
    form.regionId = undefined;
    form.regionPositionId = undefined;
    regionPositionList.value = [];
  }
}

const getRegionPosition = async () => {
  let res = await getRegionPositionApi(form.regionId);
  if (res.data.data.length > 0) {
    regionPositionList.value = res.data.data;
  } else {
    form.regionPositionId = undefined;
    regionPositionList.value = [];
  }
}

const submit = () => {
  if (!formRef) return
  formRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      let res;
      let text = "创建";
      if (props.mode == "add") {
        res = await createDeviceApi(form);
      } else {
        res = await editDeviceApi(form);
        text = "编辑";
      }
      if (res.data.code == 0) {
        ElMessage.success(`${text}成功`)
        emit('afterSubmit', '')
        dialogFormVisible.value = false;
      }
    } else {
      return false
    }
  })
}

watch([dialogFormVisible], (newVal: Array<any>) => {
  if (newVal[0] === false) {
    formRef?.value?.resetFields();
    Object.assign(form, {
      id: 0,
      productId: undefined,
      deviceCode: undefined,
      deviceName: undefined,
      regionId: undefined,
      regionPositionId: undefined,
      regionList: undefined,
    })
    regionPositionList.value = []
  }
})
watch(() => form.regionId, (newVal) => {
  if (newVal) getRegionPosition();
})

defineExpose({
  dialogFormVisible,
  form
})
</script>

<style scoped>

</style>